package com.etrans.web.gps.business.base.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.etrans.web.gps.base.service.BaseService;
import com.etrans.web.gps.business.base.domain.AreaVO;
import com.etrans.web.gps.business.base.domain.EnterpriseVO;
import com.etrans.web.gps.business.base.domain.PlatformVO;
import com.etrans.web.gps.business.base.domain.PubOrganzation;
import com.etrans.web.gps.util.ParseXml;
import com.etrans.web.gps.util.WebServiceUtil;

/**
 * 业户信息管理Service
 * @author zhangw
 *
 */
@Service
public class EnterpriseService extends BaseService{
	
	/**
	 * 加载所属区域列表
	 */
	public List<AreaVO> queryAreaTreesExtend(HashMap<String, Object> param) {
		return selectList("EnterpriseQusery.queryAreaTreesExtend",param);
	}
	
	/**
	 * 加载经营范围列表
	 */
	public List<HashMap<String,Object>> queryBizScopeList() {
		return selectList("EnterpriseQusery.queryBizScopeList",null);
	}
	
	/**
	 * 分页查询业户信息
	 */
	public List<EnterpriseVO> loadEnterpriseList(Map<String, Object> paramMap) {
		//查询所有区域列表
		List<AreaVO> areaList = selectList("EnterpriseQusery.queryAreaTreesExtend",null);
		Map<String,String> areaMap = new HashMap<String,String>();
		for (AreaVO areaVO : areaList) {
			areaMap.put(areaVO.getFullId(), areaVO.getName());		
		}
		//查询并遍历
		List<EnterpriseVO> enterpriseList = selectList("EnterpriseQusery.queryEnterpriseList",paramMap);
		String areaName  = null;
		//判断业户信息中是否填写了所属区域
		for (EnterpriseVO enterpriseVO : enterpriseList) {
			String fullId= enterpriseVO.getAreaFullId();
			if (fullId != null) {
				Integer lenth = fullId.length();
				if (lenth > 18) {
					String gParentFullId = fullId.substring(0, 8);
					String parentFullId = fullId.substring(0, 17);
					String gParentName = areaMap.get(gParentFullId) == null ? "" : areaMap.get(gParentFullId);
					String parentName = areaMap.get(parentFullId) == null ? "" : areaMap.get(parentFullId);
					areaName = gParentName+"-"+parentName+"-"+enterpriseVO.getAreaName();
					enterpriseVO.setAreaName(areaName);
				}else if (lenth > 9) {
					String parentFullId = fullId.substring(0, 8);
					String parentName = areaMap.get(parentFullId) == null ? "" : areaMap.get(parentFullId);
					areaName = parentName+"-"+enterpriseVO.getAreaName();
					enterpriseVO.setAreaName(areaName);
				}	
			}
		}
		return enterpriseList;
	}
	/**
	 * 根据条件查询到的业户数量
	 */
	public Integer queryEnterpriseListCount(Map<String, Object> paramMap) {
		return selectOne("EnterpriseQusery.queryEnterpriseListCount",paramMap);
	}
	/**
	 *查询许可证号是否已被使用，即是否重复
	 */
	public int queryCountByBizLicenseNum(HashMap<String, Object> paramMap) {
		return selectOne("EnterpriseQusery.queryCountByBizLicenseNum",paramMap);
	}
	
	/**
	 * 
	 * */
	public  String queryEnterprise(Integer enterpriseId ) {
		return selectOne("EnterpriseQusery.queryEnterpriseTradeKinds",enterpriseId);
	}
	
	/**
	 * 根据ID查询业户信息
	 * @param enterpriseId
	 * @return
	 */
	public EnterpriseVO queryEnterpriseById(Integer enterpriseId) {
		//查询所有行业列表
		List<HashMap<String,Object>> tradeKindList = selectList("EnterpriseQusery.queryTradeKindList",null);
		Map<String,String> tradeKindMap = new HashMap<String,String>();
		for (HashMap<String,Object> tradeKind : tradeKindList) {
			tradeKindMap.put(String.valueOf(tradeKind.get("id")), String.valueOf(tradeKind.get("name")));		
		}
		//查询所有区域列表
		List<AreaVO> areaList = selectList("EnterpriseQusery.queryAreaTreesExtend",null);
		Map<String,String> areaMap = new HashMap<String,String>();
		for (AreaVO areaVO : areaList) {
			areaMap.put(areaVO.getFullId(), areaVO.getName());		
		}
		EnterpriseVO enterpriseVO = selectOne("EnterpriseQusery.queryEnterpriseById",enterpriseId);
		String areaName  = enterpriseVO.getAreaName();
		String fullId= enterpriseVO.getAreaFullId();
		if (fullId != null) {
			Integer lenth = fullId.length();
			if (lenth > 18) {
				String gParentFullId = fullId.substring(0, 8);
				String parentFullId = fullId.substring(0, 17);
				String gParentName = areaMap.get(gParentFullId) == null ? "" : areaMap.get(gParentFullId);
				String parentName = areaMap.get(parentFullId) == null ? "" : areaMap.get(parentFullId);
				areaName = gParentName+"-"+parentName+"-"+enterpriseVO.getAreaName();
				enterpriseVO.setAreaName(areaName);
			}else if (lenth > 9) {
				String parentFullId = fullId.substring(0, 8);
				String parentName = areaMap.get(parentFullId) == null ? "" : areaMap.get(parentFullId);
				areaName = parentName+"-"+enterpriseVO.getAreaName();
				enterpriseVO.setAreaName(areaName);
			}	
		}
		String tradekind_ids = enterpriseVO.getTradekind_ids() == null ? "" : enterpriseVO.getTradekind_ids();
		if (!"".equals(tradekind_ids)) {
			StringBuffer stb = new StringBuffer();
			String[] tradekinds = tradekind_ids.split("#");
			for (String tradeStr : tradekinds) {
				if (!"".equals(tradeStr)) {
					stb.append(tradeKindMap.get(tradeStr)+"，");
				}
			}
			enterpriseVO.setTradekind_ids(stb.toString());
		}
		return enterpriseVO;
	}
	
	
	
	
	
	
	/**
	 *保存业户信息
	 */
	public void saveEnterprise(EnterpriseVO enterprise) {
		insert("EnterpriseMapper.saveEnterprise", enterprise);
		
	}
	/**
	 *修改业户信息
	 */
	public void updateEnterprise(EnterpriseVO enterprise) {
		update("EnterpriseMapper.updateEnterprise", enterprise);
		
	}
	/**
	 *  根据ID删除业户信息
	 * @param parseInt
	 */
	public void deleteEnterpriseByID(int enterpriseId) {
		delete("EnterpriseMapper.deleteEnterpriseByID",enterpriseId);
	}
	/**
	 *  查询所有平台
	 */
	public List<PlatformVO> queryPlatformList() {
		return selectList("EnterpriseQusery.queryPlatformList",null);
	}

	/**
	 *  查询所有发证机关
	 */
	public List<PubOrganzation> queryLssuingAuthList() {
		return selectList("EnterpriseQusery.queryLssuingAuthList",null);
	}
	
	/**
	 *  查询所有经济类型
	 */
	public List<HashMap<String,Object>> queryEconomyTypeList() {
		return selectList("EnterpriseQusery.queryEconomyTypeList",null);
	}
	
	/**
	 * 根据用户名查找业户信息
	 * @return
	 */
	public Integer queryEnterpriseByName(String enterpriseName) {
		EnterpriseVO vo = selectOne("EnterpriseQusery.queryEnterpriseByName",enterpriseName);
		Integer count = 0;
		if (vo!=null) {
			count = vo.getId();
		}
		return count;
	}
	/**
	 * 判断经营许可证号是否重复
	 * @return
	 */
	public Integer queryEnterpriseByBizLicenseNum(String bizLicenseNum) {
		return selectOne("EnterpriseQusery.queryEnterpriseByBizLicenseNum",bizLicenseNum);
	}
	
	@Transactional(readOnly = false, rollbackFor = { DataAccessException.class,Exception.class })
	public void UpdateEnterpriseTradeKinds(Map<String, Object> param) {
		this.update("EnterpriseMapper.UpdateEnterpriseTradeKinds", param);		
	}
	/**
	 * 同步运政业户信息
	 * @param yhmc
	 * @param xkzh
	 * @param ziparea
	 */
	public boolean synOwnerInfo(String yhmc, String xkzh, String ziparea) {
		boolean flag = true;
		Map<String, Object> param = new HashMap<>();
		try{
			param =WebServiceUtil.getOwnerInfoXml(yhmc,xkzh,ziparea);
//			String xmlOwner = "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'><soap:Body><GetOwnerInfoResponse xmlns='http://tempuri.org/'><GetOwnerInfoResult><xs:schema id='NewDataSet' xmlns='' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'><xs:element name='NewDataSet' msdata:IsDataSet='true' msdata:UseCurrentLocale='true'><xs:complexType><xs:choice minOccurs='0' maxOccurs='unbounded'><xs:element name='Owner'><xs:complexType><xs:sequence><xs:element name='OwnerName' type='xs:string' minOccurs='0' /><xs:element name='Address' type='xs:string' minOccurs='0' /><xs:element name='MgrArea' type='xs:string' minOccurs='0' /><xs:element name='BeginDate' type='xs:string' minOccurs='0' /><xs:element name='EndDate' type='xs:string' minOccurs='0' /><xs:element name='State' type='xs:string' minOccurs='0' /><xs:element name='ID_Owner' type='xs:string' minOccurs='0' /><xs:element name='CorporateName' type='xs:string' minOccurs='0' /><xs:element name='EconomicType' type='xs:string' minOccurs='0' /><xs:element name='LicenseNumber' type='xs:string' minOccurs='0' /></xs:sequence></xs:complexType></xs:element></xs:choice></xs:complexType></xs:element></xs:schema><diffgr:diffgram xmlns:msdata='urn:schemas-microsoft-com:xml-msdata' xmlns:diffgr='urn:schemas-microsoft-com:xml-diffgram-v1'><NewDataSet xmlns=''><Owner diffgr:id='Owner1' msdata:rowOrder='0' diffgr:hasChanges='inserted'><OwnerName>遵义县鸿顺运输有限责任公司</OwnerName><Address>遵义市埌西村五组双拥路28-2号1栋4号5楼</Address><MgrArea>班车客运（县内、县际、包车客运（县内、县际）</MgrArea><BeginDate>2017-06-29</BeginDate><EndDate>2021-06-28</EndDate><State>营业</State><ID_Owner>520321004616</ID_Owner><EconomicType>有限责任公司</EconomicType><LicenseNumber>520321004616</LicenseNumber></Owner></NewDataSet></diffgr:diffgram></GetOwnerInfoResult><ErrMsg /></GetOwnerInfoResponse></soap:Body></soap:Envelope>";
//			ParseXml parse = new ParseXml();
//			param = parse.parse(xmlOwner);
			if(param.get("State")!=null){
				if("营业".equals(param.get("State").toString())){
					param.put("State", 1);
				}else{
					param.put("State", 0);
				}
			}
			if(param.get("OwnerName")!=null){
				this.update("EnterpriseMapper.synOwnerInfo", param);
			}else{
				flag = false;
			}
			return flag;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}	
	}

	public Map<String, Object> queryOwnerVoById(Integer id) {
		
		return this.selectOne("EnterpriseQusery.queryOwnerVo", id);
	}
}
